﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

#if TESTS

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;


namespace Amarok.Agents
{
	[TestFixture]
	public sealed class Test_Agent_AsyncMessageHandler
	{
		private class MyConcurrentMessage : Message
		{
		}
		private class MyExclusiveMessage : Message
		{
		}
		private class MyIndependentMessage : Message
		{
		}
		private class MyExceptionBeforeAwaitMessage : Message
		{
		}
		private class MyExceptionAfterAwaitMessage : Message
		{
		}

		private class TestAgent : Agent
		{
			public static AutoResetEvent HandlerCompletedSignal;
			public static TaskScheduler HandlerEntryTaskScheduler;
			public static TaskScheduler HandlerContinuedTaskScheduler;
			public static Int32? HandlerEntryTaskId;
			public static Int32? HandlerContinuedTaskId;


			public TestAgent(AgentEnvironment environment, AgentOptions options)
				: base(environment, options)
			{
			}


			[MessageHandler, ConcurrentExecution, ModerateParallelism]
			private async Task _HandleMyConcurrentMessage(MyConcurrentMessage message)
			{
				// capture task scheduler used to call this handler
				HandlerEntryTaskScheduler = TaskScheduler.Current;
				HandlerEntryTaskId = Task.CurrentId;

				// await something
				await Task.Factory.StartNew(() => Thread.Sleep(500));

				// capture task scheduler on continuation (after await)
				HandlerContinuedTaskScheduler = TaskScheduler.Current;
				HandlerContinuedTaskId = Task.CurrentId;

				// done
				HandlerCompletedSignal.Set();
			}

			[MessageHandler, ExclusiveExecution, ModerateParallelism]
			private async Task _HandleMyExclusiveMessage(MyExclusiveMessage message)
			{
				// capture task scheduler used to call this handler
				HandlerEntryTaskScheduler = TaskScheduler.Current;
				HandlerEntryTaskId = Task.CurrentId;

				// await something
				await Task.Factory.StartNew(() => Thread.Sleep(500));

				// capture task scheduler on continuation (after await)
				HandlerContinuedTaskScheduler = TaskScheduler.Current;
				HandlerContinuedTaskId = Task.CurrentId;

				// done
				HandlerCompletedSignal.Set();
			}

			[MessageHandler, IndependentExecution, ModerateParallelism]
			private async Task _HandleMyIndependentMessage(MyIndependentMessage message)
			{
				// capture task scheduler used to call this handler
				HandlerEntryTaskScheduler = TaskScheduler.Current;
				HandlerEntryTaskId = Task.CurrentId;

				// await something
				await Task.Factory.StartNew(() => Thread.Sleep(500));

				// capture task scheduler on continuation (after await)
				HandlerContinuedTaskScheduler = TaskScheduler.Current;
				HandlerContinuedTaskId = Task.CurrentId;

				// done
				HandlerCompletedSignal.Set();
			}
		}

		private class TestAgent2 : Agent
		{
			public static Boolean ThrowException = true;

			public TestAgent2(AgentEnvironment environment, AgentOptions options)
				: base(environment, options)
			{
			}


			[MessageHandler]
			private async Task _HandleMyExceptionBeforeAwaitMessage(MyExceptionBeforeAwaitMessage message)
			{
				if (ThrowException)
					throw new ApplicationException("BEFORE");

				// await something
				await Task.Factory.StartNew(() => Thread.Sleep(250));
			}

			[MessageHandler]
			private async Task _HandleMyExceptionAfterAwaitMessage(MyExceptionAfterAwaitMessage message)
			{
				// await something
				await Task.Factory.StartNew(() => Thread.Sleep(250));

				if (ThrowException)
					throw new ApplicationException("AFTER");
			}
		}


		[SetUp]
		public void Setup()
		{
			TestAgent.HandlerCompletedSignal = new AutoResetEvent(false);
			TestAgent.HandlerEntryTaskScheduler = null;
			TestAgent.HandlerContinuedTaskScheduler = null;
			TestAgent.HandlerEntryTaskId = -1;
			TestAgent.HandlerContinuedTaskId = -1;
		}


		// --- TESTS ---


		[Test]
		public void Test_AsyncMessageHandler_Concurrent()
		{
			var environment = new AgentEnvironment();
			var testAgent = Agent.Factory.SpawnAgent<TestAgent>(environment);

			testAgent.Post(new MyConcurrentMessage());
			TestAgent.HandlerCompletedSignal.WaitOne(5000);

			// verify that the same task scheduler was used after awaiting something
			Assert.That(TestAgent.HandlerContinuedTaskScheduler, Is.SameAs(TestAgent.HandlerEntryTaskScheduler));
			Assert.That(TestAgent.HandlerEntryTaskScheduler, Is.Not.SameAs(TaskScheduler.Default));

			// verify that a task change happened, meaning that await didn't complete synchronously
			Assert.That(TestAgent.HandlerEntryTaskId, Is.Not.Null);
			Assert.That(TestAgent.HandlerContinuedTaskId, Is.Not.EqualTo(TestAgent.HandlerEntryTaskId));
		}

		[Test]
		public void Test_AsyncMessageHandler_Exclusive()
		{
			var environment = new AgentEnvironment();
			var testAgent = Agent.Factory.SpawnAgent<TestAgent>(environment);

			testAgent.Post(new MyExclusiveMessage());
			TestAgent.HandlerCompletedSignal.WaitOne(5000);

			// verify that the same task scheduler was used after awaiting something
			Assert.That(TestAgent.HandlerContinuedTaskScheduler, Is.SameAs(TestAgent.HandlerEntryTaskScheduler));
			Assert.That(TestAgent.HandlerEntryTaskScheduler, Is.Not.SameAs(TaskScheduler.Default));

			// verify that a task change happened, meaning that await didn't complete synchronously
			Assert.That(TestAgent.HandlerEntryTaskId, Is.Not.Null);
			Assert.That(TestAgent.HandlerContinuedTaskId, Is.Not.EqualTo(TestAgent.HandlerEntryTaskId));
		}

		[Test]
		public void Test_AsyncMessageHandler_Independent()
		{
			var environment = new AgentEnvironment();
			var testAgent = Agent.Factory.SpawnAgent<TestAgent>(environment);

			testAgent.Post(new MyIndependentMessage());
			TestAgent.HandlerCompletedSignal.WaitOne(5000);

			// verify that the same task scheduler was used after awaiting something
			Assert.That(TestAgent.HandlerContinuedTaskScheduler, Is.SameAs(TestAgent.HandlerEntryTaskScheduler));
			Assert.That(TestAgent.HandlerEntryTaskScheduler, Is.SameAs(TaskScheduler.Default));

			// verify that a task change happened, meaning that await didn't complete synchronously
			Assert.That(TestAgent.HandlerEntryTaskId, Is.Not.Null);
			Assert.That(TestAgent.HandlerContinuedTaskId, Is.Not.EqualTo(TestAgent.HandlerEntryTaskId));
		}

		[Test]
		public void Test_AsyncMessageHandler_ExceptionBeforeAwait()
		{
			var signal = new AutoResetEvent(false);
			Exception exception = null;

			DefaultDispatcherHooks.MessageHandlerFailed = (msg, e) =>
				{
					exception = e;
					signal.Set();
				};

			var environment = new AgentEnvironment();
			var testAgent = Agent.Factory.SpawnAgent<TestAgent2>(environment);

			testAgent.Post(new MyExceptionBeforeAwaitMessage());
			signal.WaitOne(5000);

			Assert.That(exception, Is.Not.Null);
			Assert.That(exception.Message, Is.EqualTo("BEFORE"));
		}

		[Test]
		public void Test_AsyncMessageHandler_ExceptionAfterAwait()
		{
			var signal = new AutoResetEvent(false);
			Exception exception = null;

			DefaultDispatcherHooks.MessageHandlerFailed = (msg, e) =>
				{
					exception = e;
					signal.Set();
				};

			var environment = new AgentEnvironment();
			var testAgent = Agent.Factory.SpawnAgent<TestAgent2>(environment);

			testAgent.Post(new MyExceptionAfterAwaitMessage());
			signal.WaitOne(5000);

			Assert.That(exception, Is.Not.Null);
			Assert.That(exception.Message, Is.EqualTo("AFTER"));
		}

	}
}

#endif
